#=
测试哈密顿量构造
=#


include("../src/edmary.jl")

using ..edmary

using SparseArrays
using LinearAlgebra
using Arpack: eigs
using Dates
using JLD2


function saveCSC(fh, name)
    if isfile(name)
        rm(name)
    end
    handle = jldopen(name, "w")
    write(handle, "CSC", fh)
    close(handle)
end


function loadCSC(name)
    handle = jldopen(name, "r")
    csc = read(handle, "CSC")
    close(handle)
    return csc
end


function fullham2()
    L = 4
    npart = 5
    nsite = L^2
    U = 3.0
    t1 = -1.0
    t2 = -0.0
    name = "L$(L)npart$(npart)nsite$(nsite)U$(U)t1$(t1)t2$(t2).jld"
    sta, invsta = get_state_array(npart, nsite)
    println(length(sta))
    @show Dates.now()
    bonds = bonds_ckb(L, t1, t2)
    if isfile(name)
        fh = loadCSC(name)
    else
        fh = full_hmltCSC(npart, nsite, sta, invsta, bonds, U)
        saveCSC(fh, name)
    end
    @show Dates.now()
    #println(Matrix(fh))
    #
    #nurand = rand(length(sta))
    #nutmp = zeros(length(sta))
    #apply_hmlt!(nutmp, nurand, nsite, sta, invsta, bonds, U)
    #println(nutmp)
    #println(fh*nurand)
    #@show Dates.now()
    #@assert all(isapprox.(nutmp, fh*nurand, atol=1e-10))
    #@show Dates.now()
    #
    v0r = rand(length(sta))
    v0r = v0r / norm(v0r)
    eval, evec = eigs(fh; nev=2, which=:SR, tol=0.0, maxiter=100, sigma=nothing, ritzvec=true, v0=v0r)
    println(eval)
    @show Dates.now()
    #
    coef1 = sqrt(3)/2
    coef2 = complex(0.0, 1/2)
    ppbonds = ppbonds_ckb(L,
    Dict("+x"=>coef1, "+y"=>-coef1, "-x"=>coef1, "-y"=>-coef1, "+x+y"=>coef2, "-x-y"=>coef2),
    Dict("+x"=>coef1, "+y"=>-coef1, "-x"=>coef1, "-y"=>-coef1, "+x-y"=>coef2, "-x+y"=>coef2),
    )
    corr = ppbuild_from_order_param(ppbonds, [1, 1+L])
    #println(corr[2*12*16+1:2*12*16+12])
    #return
    #corr2 = [
    #    (2, :dn, 1, :up, 1, :up, 2, :dn, 1),
    #    (5, :dn, 1, :up, 1, :up, 5, :dn, 1)
    #]
    #corr2 = corr[7:7]
    #println(corr2)
    #corr2 = vcat(corr[1+12:12+12], corr[12*16+1+12:12*16+12+12], corr[2*12*16+1+12:2*12*16+12+12])
    #corr2 = vcat(corr2, corr[3*12*16+1+12:3*12*16+12+12], corr[12+4*12*16+1:4*12*16+12+12], corr[5*12*16+1+12:5*12*16+12+12])
    #corr2 = vcat(corr2, corr[6*12*16+1+12:6*12*16+12+12], corr[12+7*12*16+1:7*12*16+12+12], corr[8*12*16+1+12:8*12*16+12+12])
    #corr2 = vcat(corr2, corr[9*12*16+1+12:9*12*16+12+12], corr[12+10*12*16+1:10*12*16+12+12], corr[11*12*16+1+12:11*12*16+12+12])
    #println(corr2)
    #println(length(corr2))
    pp = full_ppCSC(npart, nsite, sta, invsta, corr, U)
    handle = jldopen("test.jld", "w")
    write(handle, "CSC", pp)
    close(handle)
end


function fullham3()
    sta, invsta = get_state_array(2, 3)
    println(sta)
    bonds = [(1, 2, -0.2), (1, 3, -0.8)]
    lanzcos_iteration(2, 3, sta, invsta, bonds, 2.0)
    vec = reconstruct_ground_state(2, 3, sta, invsta, bonds, 2.0)
    println(vec)
end



fullham2()
#fullham3()

